package com.system.enterprisemanagementsystem.service.impl;

import com.system.enterprisemanagementsystem.exception.BusinessException;
import com.system.enterprisemanagementsystem.mapper.DeptMapper;
import com.system.enterprisemanagementsystem.mapper.EmpMapper;
import com.system.enterprisemanagementsystem.pojo.Dept;
import com.system.enterprisemanagementsystem.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    public List<Dept> findAll(){
        List<Dept> list = deptMapper.findAll();
        return list;
    }


    public void deleteById(Integer id){
        // 1. 查询该部门下是否有员工
        Long count = empMapper.countByDeptId(id);

        // 2. 如果有员工，则抛出业务异常
        if (count != null && count > 0) {
            throw new BusinessException("对不起，当前部门下有员工，不能直接删除！");
        }

        // 3. 否则执行删除操作
        deptMapper.deleteById(id);

    }

    public void addDept(Dept dept){
        //补全基本属性
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        //保存部门
         deptMapper.addDeptByName(dept);
    }

    public Dept getDeptById(Integer id){
        return deptMapper.getDeptById(id);
    }

    public void updateDept(Dept dept){
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
}
